package config

import (
	"context"
	"errors"
	"gitee.com/liuxuezhan/ar-platform/assets-rpc/internal/dao/schema/config"
	"gitee.com/liuxuezhan/ar-platform/assets-rpc/internal/svc"
	"github.com/zeromicro/go-zero/core/logx"
	"gorm.io/gorm"
)

type InoutModel struct {
	ctx context.Context
	db  *gorm.DB
	logx.Logger
}

func NewInoutModel(ctx context.Context, db *gorm.DB) *InoutModel {
	return &InoutModel{
		ctx:    ctx,
		db:     db,
		Logger: logx.WithContext(ctx),
	}
}

func (m *InoutModel) getDb() *gorm.DB {
	if m.db != nil {
		return m.db
	}

	return svc.Db
}

// All 获取所有记录
func (m *InoutModel) All() ([]config.ConfigInoutType, error) {
	var models []config.ConfigInoutType

	result := m.getDb().Find(&models)
	if err := result.Error; err != nil {
		return models, err
	}
	return models, nil
}

// FindByTypeId 获取一条记录
func (m *InoutModel) FindByTypeId(typeId int64) (*config.ConfigInoutType, error) {
	var model config.ConfigInoutType

	result := m.getDb().Where("type_id = ? and deleted_at is null", typeId).First(&model)
	if err := result.Error; err != nil {
		return nil, err
	}
	return &model, nil
}

// FindById 获取一条记录
func (m *InoutModel) FindById(id int64) (*config.ConfigInoutType, error) {
	var model config.ConfigInoutType
	result := m.getDb().Where("id = ?", id).First(&model)
	if err := result.Error; err != nil {
		return nil, err
	}
	return &model, nil
}

// FindByIds 获取多条记录
func (m *InoutModel) FindByIds(ids []int64) ([]*config.ConfigInoutType, error) {
	var model []*config.ConfigInoutType
	result := m.getDb().Where("id in ?", ids).Find(&model)
	if err := result.Error; err != nil {
		return nil, err
	}
	return model, nil
}

// Exists 判断余额变动类型是否存在
func (m *InoutModel) Exists(typeId int64) (bool, *config.ConfigInoutType, error) {
	var model config.ConfigInoutType

	result := m.getDb().Where("type_id = ? ", typeId).First(&model)
	if err := result.Error; err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return false, nil, nil
		}
		return false, nil, err
	}
	return true, &model, nil
}

// Add 创建数据
func (m *InoutModel) Add(data config.ConfigInoutType) (id int64, err error) {
	result := m.getDb().Create(&data)
	if result.Error != nil {
		err = result.Error
		return
	}
	id = data.Id
	return
}

// Edit 编辑
func (m *InoutModel) Edit(id int64, data config.ConfigInoutType) (err error) {
	result := m.getDb().Where("id= ? ", id).Updates(data)
	if result.Error != nil {
		err = result.Error
		return
	}
	return
}
